package com.xw.studyone.progress

import android.annotation.SuppressLint
import android.app.*
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.*
import android.widget.RemoteViews
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.xw.studyone.IDownLoadListener
import com.xw.studyone.IMyService
import com.xw.studyone.R

class MyService : Service() {

    private val MUSIC_NOTIFY_PLAYER_ID = 11
    private val GROUP_ID = "download_group"
    private val GROUP_NAME = "下载组"
    private val CHANNEL_ID = "download_channel"
    private val CHANNEL_NAME = "下载控制"

    private var mActionPlay = ".start"
    private var mActionClose = ".close"

    private lateinit var actionReceiver: ActionReceiver
    private lateinit var mManager: NotificationManager

    private var mSimpleContentView: RemoteViews? = null

    private lateinit var handler2: Handler

    private var handler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)

            when(msg.what) {

                1 -> {
                    mSimpleContentView?.setTextViewText(R.id.tv_progress, "下载进度：$progress%")
                }

                2 -> {
                    mSimpleContentView?.setImageViewResource(R.id.image_start,R.mipmap.float_image_start)
                }

                3 -> {
                    mSimpleContentView?.setImageViewResource(R.id.image_start,R.mipmap.float_image_stop)
                }
            }

            updateNitification()

        }
    }


    private var progress:Int = 0
    private var state: Int = 0
    private var mBinder: BrigeImpl? = null

    private val mDownloadListenerList: RemoteCallbackList<IDownLoadListener> = RemoteCallbackList<IDownLoadListener>()

    override fun onCreate() {
        super.onCreate()

        initReceiver()
        mManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        handler2 = Handler()
    }

    @SuppressLint("RemoteViewLayout")
    private fun createNotication() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNoticationChannel()
        }

        if (mSimpleContentView == null) {
            mSimpleContentView = RemoteViews(packageName, R.layout.music_notify_player_small)
            setListener(mSimpleContentView!!)
        }

        val notification = NotificationCompat.Builder(this,CHANNEL_ID)
            .setContentTitle("测试标题")
            .setContent(mSimpleContentView)
            .setSmallIcon(R.mipmap.float_music_icon)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .build()

        notification.flags = notification.flags or Notification.FLAG_ONGOING_EVENT
        startForeground(MUSIC_NOTIFY_PLAYER_ID,notification)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun createNoticationChannel() {

        val group = NotificationChannelGroup(GROUP_ID,GROUP_NAME)
        mManager.createNotificationChannelGroup(group)

        val channel = NotificationChannel(CHANNEL_ID,CHANNEL_NAME,NotificationManager.IMPORTANCE_LOW)
        channel.group = GROUP_ID
        //在所迫的时候显示全部内容

        channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
        mManager.createNotificationChannel(channel)
    }

    private fun updateNitification() {
        // 重新构建并更新通知
        val notification = NotificationCompat.Builder(this,CHANNEL_ID)
            .setContentTitle("测试标题")
            .setContent(mSimpleContentView)
            .setSmallIcon(R.mipmap.float_music_icon)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .build()

        mManager.notify(MUSIC_NOTIFY_PLAYER_ID, notification)
    }


    private fun setListener(view: RemoteViews) {
        try {

            var pendingIntent = PendingIntent.getBroadcast(applicationContext,0,
                Intent(mActionPlay).setPackage(packageName),PendingIntent.FLAG_UPDATE_CURRENT)
            view.setOnClickPendingIntent(R.id.image_start,pendingIntent)

            pendingIntent = PendingIntent.getBroadcast(applicationContext,0,
                Intent(mActionClose).setPackage(packageName),PendingIntent.FLAG_UPDATE_CURRENT)
            view.setOnClickPendingIntent(R.id.image_cancle,pendingIntent)

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    private fun initReceiver() {

        val packgeName = packageName
        actionReceiver = ActionReceiver()

        mActionPlay = packgeName + mActionPlay
        mActionClose = packgeName + mActionClose

        val filter = IntentFilter()
        filter.addAction(mActionPlay)
        filter.addAction(mActionClose)

        registerReceiver(actionReceiver,filter)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {

        createNotication()
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent): IBinder? {
        //这个是aidl 返回对象
        if (mBinder == null) {
            mBinder = BrigeImpl()
        }
        return mBinder
    }
    
    private inner class BrigeImpl: IMyService.Stub() {

        override fun pause() {
            state = 0
            handler.sendEmptyMessage(2)
        }

        override fun start(url: String?) {
            state = 1
            handler2.post(runnable)
            handler.sendEmptyMessage(3)
        }

        override fun close() {
            state = 0
            handler2.removeCallbacks(runnable)
            closeService()
        }

        override fun registerOnDownloadListener(listener: IDownLoadListener?) {
            mDownloadListenerList.register(listener)
        }

        override fun unregisterOnDownloadListener(listener: IDownLoadListener?) {
           mDownloadListenerList.unregister(listener)
        }

    }

    private inner class ActionReceiver: BroadcastReceiver() {

        override fun onReceive(p0: Context?, p1: Intent?) {

            when(p1?.action) {

                mActionPlay -> {
                    if (state == 0) {
                        state = 1
                        handler2.post(runnable)
                        handler.sendEmptyMessage(3)
                    } else {
                        state = 0
                        handler2.removeCallbacks(runnable)
                        handler.sendEmptyMessage(2)
                    }
                }

                mActionClose -> {
                    state = 0
                    handler2.removeCallbacks(runnable)
                    closeService()
                }

                else -> {

                }
            }

        }
    }

    private val runnable: Runnable = object : Runnable {
        override fun run() {
            if (state > 0) {
                progress++
                handler.sendEmptyMessage(1)
                val count = mDownloadListenerList.beginBroadcast()
                for ( i in 0 until count) {
                    val downloads = mDownloadListenerList.getBroadcastItem(i)
                    downloads.onProgressChange(progress)
                }

                mDownloadListenerList.finishBroadcast()
                if (progress >= 100) {
                    handler2.removeCallbacks(this)
                } else {
                    handler2.postDelayed(this, 1000)
                }
            }

        }
    }


    private fun closeService() {
        stopForeground(true)
        mManager.cancel(MUSIC_NOTIFY_PLAYER_ID)
        stopSelf()
    }

    override fun onDestroy() {
        super.onDestroy()
        handler2.removeCallbacksAndMessages(runnable)
        handler.removeCallbacksAndMessages(null)
    }

}